<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    /* 
      https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof/
      思路：https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof/solution/si-lu-jian-dan-gen-ju-ceng-shu-lai-jin-xing-revers/

      输入示例：
          3
         / \
        9  20
          /  \
         15   7
      输出示例：遍历顺序为 -> 一行从左到右，一行从右到左
        [
          [3],
          [20,9],
          [15,7]
        ]
     */
    function levelOrder(root) {
      if (!root)  return []
      const res = []
      const queue = [root]
      let level = 0

      while (queue.length) {
        res[level] = []
        let levelNum = queue.length

        while (levelNum--) {
          let first = queue.shift()
          res[level].push(first.val)
          first.left && queue.push(first.left)
          first.right && queue.push(first.right)
        }

        if (level & 1) {
          res[level].reverse()
        }

        level++
      }

      return res
    }
  </script>
</body>
</html>